import re
import urllib.parse as urlparse

from mini_web import request


def GET(request_data):
    # 获取请求url
    url_data = request_data.split("\n")[0]
    url_data = url_data.split(" ")
    url = url_data[1]
    # 解析url参数
    parsed = urlparse.urlparse(url)
    url = parsed.path
    # 获取查询参数
    args = urlparse.parse_qs(parsed.query)
    return request.Request("GET", url, args=args)


def POST(request_data):
    # 先解析url参数
    requestobj = GET(request_data)
    json_str = re.sub('\'', '\"', request_data)  # 单引号转双引号, json.loads 必须使用双引号

    # 获取json数据
    json_data = json_str.split("\r\n")[-1]
    requestobj.json = json_data
    return requestobj


def analysis(request_data: str):

    # 只考虑 get post请求
    func_map = {"GET": GET, "POST": POST}
    if len(request_data) > 10:
        analysis_data = request_data.split("\n")[0]
        for k, v in func_map.items():
            if re.match(k, analysis_data):
                return v(request_data)
    return None


